import { Community } from "../Community"
import serialPort from "libserialport.so";
import Logger from '../utils/Logger';
import worker from '@ohos.worker'

let TAG = '[IdoUart]'

export class CommunityUart implements Community {
  private uartFd: number = -1;
  private oTimer = null

  private port: string = "/dev/ttyS0" //串口路径
  private speed: number = 9600 //串口波特率
  private weight: number = 0;
  /**
   * 当重量发生变化的监听事件
   */
  private listener;

  // 定时器事件
  private handler = () => {
    // 如果连结已经被关闭，那么关闭连接
    if (this.uartFd == -1) {
      clearInterval(this.oTimer); // 清除定时器
      return;
    }
    Logger.info(TAG, `${serialPort}`);
    let ret: string = serialPort.read(); // 读取串口数据
    // 检查是否获取到了新的书
    if (ret != null) {
      this.weight = Number(ret);
      this.listener(this.getWeight())
    }
  }


  /**
   * 初始化，打开串口，和调用故障处理函数
   */
  public init(): void {
    if (this.uartFd != -1) {
      throw new Error('uart fd is null');
      return;
    }

    this.uartFd = serialPort.open(this.port, this.speed);
    clearInterval(this.oTimer); // 清除之前的定时器
    if (this.oTimer == null)
      this.oTimer = setInterval(this.handler, 100); // 设置定时器间隔为 100ms
  };

  /**
   * 断开链接
   */
  close(): void {
    if (this.uartFd != -1) { // 检查 uartFd 是否为有效值
      clearInterval(this.oTimer); // 清除定时器
      serialPort.close(); // 关闭串口连接
      this.uartFd = -1;
    }
  }

  setWeightListener(listener: (weight: any) => void) {
    this.listener = listener;
  }

  getWeight(): number {
    return this.weight;
  }
}
